<template>
<div class="list">
  <div class="list__wapper">
    <div class="list__title">
      <div class="list-left__menu">
        <!-- <span class="list__menu"
              @click.stop="showAdd">
            <i class="icon iconfont icon-zhankai"></i>{{$t('config.agent.addAgent')}}</span> -->
        <span class="list__menu"
              @click.stop="showBatch">
          <i class="icon iconfont icon-beizhu"></i>{{$t('config.agent.bacthEdit')}}</span>
        <span class="list__menu" @click.stop="refrech">
          <el-button class="icon
                     iconfont icon-shuaxin"
                     type="text"
                     :loading="refreshLoading"></el-button>{{$t('public.refresh')}}</span>
        <el-popover placement="bottom"
                    trigger="click"
                    v-model="visible">
          <lead-in @lindInTemSuc="closePop" @closePopover="closePopover"></lead-in>
          <span slot="reference"
                class="list__menu"><i class="icon iconfont icon-daoru"></i>{{$t('agentSetting.agentSetting23')}}</span>
        </el-popover>
         <span class="list__menu"
               v-if="isExportExcel"
               @click.stop="exportExcel">
          <i class="icon iconfont icon-daochu1"></i>{{$t('agentSetting.agentSetting24')}}</span>
        <span class="list__menu"
              v-if="isSetAgantMsg"
              @click.stop="setMessageSocket">
          <i class="icon iconfont icon-beizhu"></i>{{$t('agentSetting.agentSetting25')}}</span>
        <span class="list__menu"
              @click.stop="showConfigAgent">
          <i class="icon iconfont icon-beizhu"></i>{{$t('configLazyLoad.agentConfig.otherGroup')}}</span>
          <!-- <i class="icon iconfont icon-xiazai"></i> -->
      </div>
      <pagination class="list-right__menu" :small="true"
                                           :currentPage="trunPage"
                                           :count="total"
                                           @turnPage="trunPages"
                                           :totalPage="Math.ceil(total/10)"></pagination>
    </div>
    <agent-table :tableData = "tableData"
                 ref = "tableData"
                 @removeLock="refrech"
                 @updateUser = "updateUser"></agent-table>
    <bacth-edit-agent-info :isBacth="isBacth"
                           :total = "total"
                           @close = "closeBacth"
                           @openBatch = "showBatch"
                           @batchCancelWechatHelperBind = "batchCancelWechatHelperBind"
                           @BacthEditAgentInfo = "BacthEditAgentInfo"></bacth-edit-agent-info>
    <edit-agent :isEdit = "isEdit"
                @close="closeBacth"
                ref="recommendedPwd"
                :agentDetail = "agentDetail"
                @unbindWebchat = "unbindWebchat"
                @EditAgent = "editAgent"></edit-agent>
    <el-dialog :close-on-click-modal="false" :title="$t('agentSetting.agentSetting25')" :visible.sync="isOpenDialog" class='call-label-dialog' width="50%">
      <div>
        <div style="padding: 0px 20px 20px 20px">
          <div v-if="urls.length === 0">{{$t('agentSetting.agentSetting26')}}</div>
          <div class="url-item" v-for="(item, index) in urls" :key="index">
            <template v-if="urls.length !== 0">
              <span class="urlItem">{{item.url}}</span>
              <span @click.stop="showEditCustUrl(item)" class="edit">{{$t('public.edit')}}</span>
              <span @click.stop="delCustUrl(item)" class="del">{{$t('public.delete')}}</span>
            </template>
          </div>
          <el-button class="primary_btn" style="margin-top: 20px;" @click="showAddUrl">+ {{$t('agentSetting.agentSetting27')}}</el-button>
        </div>
        <div style="padding: 0 20px 40px 20px;" v-if="isShowAddUrlWrap">
          <strong v-if="urlAddOrEditState === 'add'">{{$t('agentSetting.agentSetting27')}}</strong>
          <strong v-if="urlAddOrEditState === 'edit'">{{$t('agentSetting.agentSetting28')}}</strong><br/>
          <div style="margin: 10px 0;">
            <span style="margin-right: 20px;">{{$t('agentSetting.agentSetting29')}}</span>
            <el-input style="width: 350px;" v-model="urlForm.url"></el-input><br/>
          </div>
          <div>
            <el-button @click.stop="resetUrlForm" class='primary_btn'>{{$t('public.cancel')}}</el-button>
            <el-button type="primary" @click="saveUrl" class='primary_btn'>{{$t('public.confirm')}}</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :title="$t('configLazyLoad.agentConfig.otherGroup')" :visible.sync="isAgentDia" width="40%">
      <div class="wrap_stop">
        <span>{{$t('configLazyLoad.agentConfig.disableGroup')}}</span>
        <el-radio-group v-model="userHidden">
          <el-radio label="yes">{{$t('public.yes')}}</el-radio>
          <el-radio label="no">{{$t('public.no')}}</el-radio>
        </el-radio-group>
        <el-tooltip
          transition="fade-leave"
          effect="dark"
          :content="$t('configLazyLoad.agentConfig.tip1')"
          placement="bottom">
          <i class="icon iconfont icon-tixingweizhi"></i>
        </el-tooltip>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click.stop="saveAgentDeal" class="primary_btn">{{$t('public.save')}}</el-button>
      </div>
    </el-dialog>
    <!-- <add-agent :isAdd="isAdd"
               @close= "closeBacth"></add-agent> -->
    <!-- <keep-alive>
      <component :is="activeName"
                 :isBacth="isBacth"
                 :total = "total"
                 @close = "closeBacth"
                 @openBatch = "showBatch"
                 @BacthEditAgentInfo = "BacthEditAgentInfo"
                 :isEdit = "isEdit"
                 :agentDetail = "agentDetail"
                 @EditAgent = "editAgent"
                 :isAdd="isAdd"></component>
    </keep-alive> -->
  </div>
</div>
</template>
<script>
  // import AddAgent from './SearchAgentListBase/AddAgent'
  import affix from '@components/ui-modules/affix/Affix.vue'
  import AgentTable from './SearchAgentListBase/AgentTable'
  import BacthEditAgentInfo from './SearchAgentListBase/BacthEditAgentInfo'
  import EditAgent from './SearchAgentListBase/EditAgent'
  import leadIn from './SearchAgentListBase/leadInTemplate'
  import Pagination from '@/components/public-modules/card/Pagination'
  import { deepClone, isHasMenu } from '@/utils/m7Utils'
  export default {
    name: 'SearchAgentList',
    data () {
      return {
        userHiddenDoc: {}, // 停用座席不参与筛选
        userHidden: 'no', // 停用座席不参与筛选绑定值
        isSetAgantMsg: false,
        isOpenDialog: false,
        isAgentDia: false, // 设置座席弹窗
        isShowAddUrlWrap: false,  //  添加客户推送接口  窗口
        urlForm: {
          url: ''
        },
        urlAddOrEditState: '',
        urls: [],
        visible: false,
        activeName: 'EditAgent',
        isBacth: false,
        creatBatch: false,
        isEdit: false,
        isAdd: false,
        refreshLoading: false,
        agentDetail: {},
        isExportExcel: false // 导出座席信息的权限
      }
    },
    components: {
      // AddAgent,
      affix,
      AgentTable,
      Pagination,
      BacthEditAgentInfo,
      EditAgent,
      leadIn
    },
    props: {
      tableData: Array,
      trunPage: Number,
      total: Number,
      propsForm: Object
    },
    watch: {
      $route () {
        this.visible = false
      }
    },
    methods: {
      // 保存是否隐藏座席
      saveAgentDeal () {
        let data = {
          userHidden: this.userHidden,
          flag: 'userHidden'
        }
        if (this.userHiddenDoc._id) {
          data._id = this.userHiddenDoc._id
        }
        this.$store.dispatch('updateUserInfoOutflow', data).then(res => {
          if (res.success) {
            this.$message.success(this.$t('monitor.saveSuccess'))
            this.isAgentDia = false
            this.userHiddenDoc = res.data
          }
        })
      },
      setMessageSocket () {
        this.isOpenDialog = true
        this.urlAddOrEditState = ''
        this.resetUrlForm()
      },
      showConfigAgent () {
        this.isAgentDia = true
      },
      resetUrlForm () {
        this.isShowAddUrlWrap = false
        this.urlForm.url = 'http'
      },
      saveUrl () {
        let data = {}
        data.url = this.urlForm.url
        let urlStr = this.urlForm.url.substring(0, 5)
        if (!(urlStr === 'http:' || urlStr === 'https')) {
          this.$message.error(this.$t('agentSetting.agentSetting30'))
          return
        }
        if (this.urlAddOrEditState === 'add') {
          this.$store.dispatch('addUserInfoOutflow', data).then(res => {
            if (res.success) {
              this.searchUrls()
              this.resetUrlForm()
            }
          })
        } else {
          data._id = this.urlForm._id
          data.flag = 'url'
          this.$store.dispatch('updateUserInfoOutflow', data).then(res => {
            if (res.success) {
              this.searchUrls()
              this.resetUrlForm()
            }
          })
        }
      },
      showAddUrl () {
        this.urlAddOrEditState = 'add'
        this.isShowAddUrlWrap = true
        this.urlForm.url = 'http'
      },
      showEditCustUrl (item) {
        this.urlAddOrEditState = 'edit'
        this.isShowAddUrlWrap = true
        this.urlForm.url = item.url
        this.urlForm._id = item._id
      },
      delCustUrl (item) {
        this.isShowAddUrlWrap = false
        let data = {}
        data._id = item._id
        data.account = this.$store.state.session.user.account
        this.$confirm(this.$t('agentSetting.agentSetting56'), this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('deleteUserInfoOutflow', data).then(resp => {
            if (resp.success) {
              this.$message.success(this.$t('sms.successDel'))
              this.searchUrls()
            } else {
              this.$message.error(this.$t('sms.failDel'))
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('public.cancel')
          })
        })
      },
      searchUrls () {
        this.$store.dispatch('queryUserInfoOutflow', null).then(res => {
          if (res.success) {
            this.urls = res.urlDocs
            this.userHiddenDoc = res.userHiddenDoc
            this.userHidden = res.userHiddenDoc.userHidden || 'no'
          }
        })
      },
      batchCancelWechatHelperBind (data) {
        this.$store.dispatch('batchCancelWechatHelperBind', data)
        .then((res) => {
          res && res.success &&
          this.$message({
            message: this.$t('agentSetting.agentSetting31'),
            type: 'success'
          })
        })
        .then(() => {
          this.$emit('refrech')
        })
      },
      // 解绑单个座席客服助手
      unbindWebchat (id) {
        let data = {
          userId: id
        }
        this.$store.dispatch('cancelWechatHelperBind', data)
        .then((res) => {
          res && res.success &&
          this.$message({
            message: this.$t('agentSetting.agentSetting32'),
            type: 'success'
          })
        })
        .then(() => {
          this.$emit('refrech')
        })
      },
      // 导入模板成功
      closePop () {
        window.localStorage.setItem('userImportStatus', 'ture')
        this.visible = false
      },
      // 单纯得关闭popover
      closePopover () {
        this.visible = false
      },
      // 刷新数据，向父组件传递刷新事件
      refrech () {
        if (window.localStorage.getItem('userImportStatus')) {
          let data = {}
          this.$store.dispatch('queryMyLatestTask', data)
          .then((res) => {
            if (res.data.flag === 'failure') {
              this.$message.error(res.data.reason)
              window.localStorage.setItem('userImportStatus', '')
            } else if (res.data.flag === 'import') {
              this.$message.error(this.$t('agentSetting.agentSetting33'))
              return
            } else if (res.data.flag === 'finish') {
              let failNum = res.data.importResult.sum - res.data.importResult.success
              window.localStorage.setItem('userImportStatus', '')
              this.$message.success(this.$t('agentSetting.agentSetting68', {'successNum': res.data.importResult.success, 'failNum': failNum}))
            }
          })
        }
        this.refreshLoading = true
        window.setTimeout(() => {
          this.refreshLoading = false
        }, 400)
        this.$emit('refrech')
      },
      // 像父组件传递翻页事件，并向上级传递第几页的数据
      trunPages (page) {
        this.$emit('trunPages', page)
      },
      // 批量修改座席，成功之后刷新数据
      BacthEditAgentInfo (data) {
        this.$store.dispatch('batchUpdateUser', data)
        .then((res) => {
          if (res && res.success) {
            if (res.hasSecondaryExten) {
              this.$message({
                message: this.$t('agentSetting.agentSetting34'),
                type: 'success'
              })
              return
            }
            this.$message({
              message: this.$t('config.agent.bacthEditSuccess'),
              type: 'success'
            })
          }
        })
        .then(() => {
          this.$emit('refrech')
        })
      },
      exportExcel () {
        if (this.total <= 0) {
          this.$message.warning(this.$t('agentSetting.agentSetting35'))
          return false
        }
        let data = {}
        data.Method = 'exportUser'
        let actionData = deepClone(this.$store.state.config.agentConfig.queryAgent) || {}
        if (actionData) {
          delete actionData.page
          delete actionData.limit
        }
        data.Query = actionData
        this.$store.dispatch('exportUserExcel', data).then(resp => {
        })
        this.$message.success(this.$t('business.exportTip'))
      },
      // 修改座席，成功之后刷新数据
      editAgent (data) {
        this.$store.dispatch('updateUser', data)
        .then((res) => {
          if (res && res.success) {
            this.$message({
              message: this.$t('config.agent.modifyAgentSuccess'),
              type: 'success'
            })
          } else {
            if (res.message === 'same_account_agent_phone_repeat') {
              this.$message.error(`该号码已被${res.agentInfo}绑定，请检查您的号码！`)
            } else if (res.message === 'same_account_agent_email_repeat') {
              this.$message.error(`该邮箱已被${res.agentInfo}绑定，请检查您的邮箱！`)
            }
          }
        })
        .then(() => {
          this.$emit('refrech')
        })
      },
      showBatch () {
        this.creatBatch = true
        this.activeName = 'BacthEditAgentInfo'
        this.isBacth = true
      },
      closeBacth () {
        this.isBacth = false
        this.isEdit = false
        // this.isAdd = false
      },
      /**
       * 接收子组件tableAgent传出来需要修改座席的信息,再传给子组件EditAgent进行修改
       * 参数为要修改座席的信息
       * 展示修改弹窗
       */
      updateUser (agentId) {
        let data = agentId
        this.$store.dispatch('getUserById', data)
        .then((res) => {
          if (res && res.success) {
            this.activeName = 'EditAgent'
            this.agentDetail = res.user
            this.isEdit = true
            this.$refs.recommendedPwd.updatePwd()
          }
        })
      }
      // closeEdit () {
      //   this.isEdit = false
      // },
      // 展示添加座席
      // showAdd () {
      //   this.activeName = 'AddAgent'
      //   this.isAdd = true
      // }
      // closeAdd () {
      //   this.isAdd = false
      // }
    },
    beforeMount () {
      this.searchUrls()
      if (isHasMenu('func_user_export', this.$store.state.session.user) || this.$store.state.session.user.isAdmin) {
        this.isExportExcel = true
      }
      if (isHasMenu('func_user_info_outflow', this.$store.state.session.user) || this.$store.state.session.user.isAdmin) {
        this.isSetAgantMsg = true
      }
    }
  }
</script>
<style lang="stylus" scoped>
@import "../../../../../assets/common.styl"
.dialog-footer
  text-align center
.wrap_stop
  padding-bottom 10px
  .el-radio-group
    padding 0 8px 0 16px
.icon-tixingweizhi
  box-sizx(15px)
  border 1px solid $c-main
  border-radius 8px
  color $c-main
  font-size 12px
.list-left__menu
  span
    cursor pointer
.icon
  margin-right 4px
.list__wapper
  width 100%
  .list__title
    border 1px solid #e7e7eb
    border-bottom 0
    display flex
    align-items center
    justify-content space-between
    .list__menu
      margin-left 16px
    .iconfont
      color $c-main
.right
  float right
.url-item
  padding 6px 0
  line-height 14px
  .urlItem
    display inline-block
    width 410px
    overflow hidden
    white-space nowrap
    text-overflow ellipsis
  .edit
    color $c-main
    padding-right 20px
    cursor pointer
  .del
    color $c-pink
    cursor pointer
</style>
